package com.rui.sideup.test.socket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.UUID;

@Slf4j
public class ServerSocket extends WebSocketServer {

    private static final String TAG = "ServerSocket";

    private ServerManager _serverManager;

    public ServerSocket(ServerManager serverManager, int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
        _serverManager = serverManager;
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        log.info("Some one Connected...");


        log.info("onOpen-conn地址:" + conn.toString());
        _serverManager.clientLogin(UUID.randomUUID().toString(), conn);

        _serverManager.sendMessageToUser(conn, "连接成功...");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        log.info("Some one Closed...");

        _serverManager.clientLeave(conn);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        log.info("OnMessage:" + message.toString());
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        log.info("Socket Exception:" + ex.toString());
    }

    @Override
    public void onStart() {

    }
}